﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Globalization;
using System.Data.SqlClient;

namespace InventoryManager
{
    public partial class AddInvoiceForm_3_UserControl : UserControl
    {
        public event FormChangedHandler FormChangedEvent;

        private string _connectionString;
        private MySqlConnection _connection;
        private BindingSource _dataGridViewBindingSource;
        private DataTable _dataGridViewDataTable;
        private MySqlDataAdapter _mySqlDataAdapter;

        private Dictionary<string, string>[] _priceDictionary;

        private int _requisitionID;
        private int _customerID;

        private const string SPECIAL_COLUMN_NAME = "ทำใบกำกับ";
        private const string COLUMN_1_NAME = "จำนวน";
        private const string COLUMN_2_NAME = "หน่วย";
        private const string COLUMN_3_NAME = "น้ำหนัก (kg)";
        private const string COLUMN_4_NAME = "ชื่อสินค้า";
        private const string COLUMN_5_NAME = "ขนาด";
        private const string COLUMN_6_NAME = "ราคาหน่วยละ";
        private const string COLUMN_7_NAME = "หน่วยที่ใช้";
        private const string COLUMN_8_NAME = "จำนวนเงิน";

        public AddInvoiceForm_3_UserControl(string connectionString, int width, int height, int requisitionID)
        {
            InitializeComponent();

            _connectionString = connectionString;
            this.Width = width;
            this.Height = height;

            _requisitionID = requisitionID;

            IncludeVatUpDown.Value = Utility.GetDefaultVat();

            LoadData();
        }

        private void LoadData()
        {
            try
            {
                _connection = new MySqlConnection(_connectionString);
                _connection.Open();

                string query = "SELECT CustomerID " +
                           "FROM requisitionidcustomername WHERE requisitionid = " + _requisitionID;
                _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable customerDataTable = new DataTable();
                _mySqlDataAdapter.Fill(customerDataTable);
                _customerID = Int32.Parse(customerDataTable.Rows[0][0].ToString());

                query = "SELECT Quantity, Classifier, Weight, ProductName, Dimension, PricePerUnit, UnitName " +
                           "FROM requisitioniddescription WHERE requisitionid = " + _requisitionID;
                _mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable importedDataTable = new DataTable();
                _mySqlDataAdapter.Fill(importedDataTable);

                _dataGridViewDataTable = new DataTable();

                DataColumn dtColumn_Spec = new DataColumn(SPECIAL_COLUMN_NAME, typeof(bool));
                DataColumn dtColumn_1 = new DataColumn(COLUMN_1_NAME);
                DataColumn dtColumn_2 = new DataColumn(COLUMN_2_NAME);
                DataColumn dtColumn_3 = new DataColumn(COLUMN_3_NAME);
                DataColumn dtColumn_4 = new DataColumn(COLUMN_4_NAME);
                DataColumn dtColumn_5 = new DataColumn(COLUMN_5_NAME);
                DataColumn dtColumn_6 = new DataColumn(COLUMN_6_NAME);
                DataColumn dtColumn_7 = new DataColumn(COLUMN_7_NAME);
                DataColumn dtColumn_8 = new DataColumn(COLUMN_8_NAME);

                dtColumn_1.ReadOnly = true;
                dtColumn_2.ReadOnly = true;
                dtColumn_3.ReadOnly = true;
                dtColumn_4.ReadOnly = true;
                dtColumn_5.ReadOnly = true;
                dtColumn_6.ReadOnly = true;
                dtColumn_7.ReadOnly = true;
                dtColumn_8.ReadOnly = true;

                _dataGridViewDataTable.Columns.Add(dtColumn_Spec);
                _dataGridViewDataTable.Columns.Add(dtColumn_1);
                _dataGridViewDataTable.Columns.Add(dtColumn_2);
                _dataGridViewDataTable.Columns.Add(dtColumn_3);
                _dataGridViewDataTable.Columns.Add(dtColumn_4);
                _dataGridViewDataTable.Columns.Add(dtColumn_5);
                _dataGridViewDataTable.Columns.Add(dtColumn_6);
                _dataGridViewDataTable.Columns.Add(dtColumn_7);
                _dataGridViewDataTable.Columns.Add(dtColumn_8);
                
                _dataGridViewBindingSource = new BindingSource();
                _dataGridViewBindingSource.DataSource = _dataGridViewDataTable;
                AddInvoiceFormDataGridView.DataSource = _dataGridViewBindingSource;

                AddInvoiceFormBindingNavigator.BindingSource = _dataGridViewBindingSource;

                _priceDictionary = new Dictionary<string, string>[importedDataTable.Rows.Count];

                for (int i = 0; i < importedDataTable.Rows.Count; i++) 
                {
                    DataRow dtRow = importedDataTable.Rows[i];
                    DataRow newDtRow = _dataGridViewDataTable.NewRow();
                    
                    string clasifier = dtRow[1].ToString();
                    string selectedProduct = dtRow[3].ToString();
                    string selectedDimension = dtRow[4].ToString();
                    string pricePerUnit = dtRow[5].ToString();
                    string selectedUnit = dtRow[6].ToString();
                    _priceDictionary[i] = new Dictionary<string, string>();

                    LoadSavedPriceAndUnit(i, clasifier, selectedProduct, selectedDimension, pricePerUnit, selectedUnit);

                    newDtRow[0] = true;

                    newDtRow[COLUMN_1_NAME] = dtRow[0]; // quantity
                    newDtRow[COLUMN_2_NAME] = dtRow[1];
                    newDtRow[COLUMN_3_NAME] = dtRow[2]; // weight
                    newDtRow[COLUMN_4_NAME] = dtRow[3];
                    newDtRow[COLUMN_5_NAME] = dtRow[4];

                    newDtRow[COLUMN_6_NAME] = _priceDictionary[i][selectedUnit];
                    newDtRow[COLUMN_7_NAME] = selectedUnit;

                    if (selectedUnit == "kg")
                        newDtRow[COLUMN_8_NAME] = Double.Parse(dtRow[2].ToString()) *
                            Double.Parse(newDtRow[COLUMN_6_NAME].ToString());
                    else
                        newDtRow[COLUMN_8_NAME] = Int32.Parse(dtRow[0].ToString()) *
                            Double.Parse(newDtRow[COLUMN_6_NAME].ToString());

                    _dataGridViewDataTable.Rows.Add(newDtRow);
                }

                PriceNumericUpDown.Value = Convert.ToDecimal(_dataGridViewDataTable.Rows[0][COLUMN_6_NAME].ToString());
                foreach (string key in _priceDictionary[0].Keys)
                    UnitComboBox.Items.Add(key);
                UnitComboBox.SelectedItem = _dataGridViewDataTable.Rows[0][COLUMN_7_NAME].ToString();

                CalculateTotal();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void LoadSavedPriceAndUnit(int rowNumber, string classifier, 
            string selectedProduct, string selectedDimension, string pricePerUnit, string selectedUnit)
        {
            string query = "SELECT PricePerWeight, PricePerItem FROM product WHERE Name = \'" + selectedProduct + "\' " +
                "AND Dimension = \'" + selectedDimension + "\'";

            MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

            DataTable dataTable = new DataTable();
            mySqlDataAdapter.Fill(dataTable);

            string pricePerWeight = dataTable.Rows[0][0].ToString();
            string pricePerItem = dataTable.Rows[0][1].ToString();

            if (selectedUnit == "kg")
            {
                double pricePerUnitVat = Double.Parse(pricePerUnit);
                _priceDictionary[rowNumber]["kg"] = pricePerUnitVat + "";
                if (pricePerItem != "")
                {
                    double pricePerItemVat = Double.Parse(pricePerItem);
                    _priceDictionary[rowNumber][classifier] = pricePerItemVat + "";
                }
            }
            else
            {
                double pricePerUnitVat = Double.Parse(pricePerUnit);
                _priceDictionary[rowNumber][classifier] = pricePerUnitVat + "";
                if (pricePerWeight != "")
                {
                    double pricePerWeightVat = Double.Parse(pricePerWeight);
                    _priceDictionary[rowNumber]["kg"] = pricePerWeightVat + "";
                }
            }
        }

        private void CalculateTotal()
        {
            if (_dataGridViewDataTable == null)
            {
                return;
            }

            double total = 0;

            foreach (DataRow dtRow in _dataGridViewDataTable.Rows)
            {
                if (!(bool)dtRow[0])
                    continue;
                total += Double.Parse(dtRow[COLUMN_8_NAME].ToString());
            }

            if (!IncludeVatCheckBox.Checked)
            {
                total *= 1 + (double)(IncludeVatUpDown.Value / 100);
            }

            TotalLabelValue.Text = total.ToString("N2", CultureInfo.InvariantCulture);
            AddInvoiceFormButton.Visible = (TotalLabelValue.Text != "0.00");
            TotalLabelName.Visible = (TotalLabelValue.Text != "0.00");
            TotalLabelValue.Visible = (TotalLabelValue.Text != "0.00");
            BahtLabel.Visible = (TotalLabelValue.Text != "0.00");
        }

        private void AddInvoiceFormButton_Click(object sender, EventArgs e)
        {
            int lastInvoiceID = -1;

            try
            {
                _connection.Open();

                // insert a new row to InvoiceIDCustomerName table
                MySqlCommand cmd = _connection.CreateCommand();
                cmd.Parameters.AddWithValue("Date", DateTime.Now);
                
                if (DeliveryNumericUpDown.Visible)
                    cmd.Parameters.AddWithValue("DeliveryPrice", DeliveryNumericUpDown.Value);
                else
                    cmd.Parameters.AddWithValue("DeliveryPrice", 0);

                if (IncludeVatCheckBox.Checked)
                    cmd.Parameters.AddWithValue("VatIncluded", true);
                else
                    cmd.Parameters.AddWithValue("VatIncluded", false);

                cmd.Parameters.AddWithValue("VatIncludedValue", IncludeVatUpDown.Value);

                cmd.CommandText = "INSERT INTO invoiceidcustomername (InvoiceID, CustomerID, Date, DeliveryPrice, VatIncluded, VatIncludedValue) " +
                    "VALUES " + "(0, \'" + _customerID + "\', ?Date, ?DeliveryPrice, ?VatIncluded, ?VatIncludedValue)";
                cmd.ExecuteNonQuery();

                // insert new rows to OrderIDDescription table and update rows in ItemsRemin column in Product table
                MySqlCommand insertCmd = _connection.CreateCommand();
                MySqlCommand updateCmd = _connection.CreateCommand();
                MySqlCommand requisitionUpdateCmd = _connection.CreateCommand();
                MySqlCommand getInvoiceIDCmd = _connection.CreateCommand();

                MySqlParameter parInvoiceID = new MySqlParameter("InvoiceID", MySqlDbType.Int32);
                MySqlParameter parQuantity = new MySqlParameter("Quantity", MySqlDbType.Int32);
                MySqlParameter parClassifier = new MySqlParameter("Classifier", MySqlDbType.VarChar);
                MySqlParameter parWeight = new MySqlParameter("Weight", MySqlDbType.Float);
                MySqlParameter parProductName = new MySqlParameter("ProductName", MySqlDbType.VarChar);
                MySqlParameter parDimension = new MySqlParameter("Dimension", MySqlDbType.VarChar);
                MySqlParameter parPricePerUnit = new MySqlParameter("PricePerUnit", MySqlDbType.Float);
                MySqlParameter parUnitName = new MySqlParameter("UnitName", MySqlDbType.VarChar);

                insertCmd.Parameters.Add(parInvoiceID);
                insertCmd.Parameters.Add(parQuantity);
                insertCmd.Parameters.Add(parClassifier);
                insertCmd.Parameters.Add(parWeight);
                insertCmd.Parameters.Add(parProductName);
                insertCmd.Parameters.Add(parDimension);
                insertCmd.Parameters.Add(parPricePerUnit);
                insertCmd.Parameters.Add(parUnitName);

                updateCmd.Parameters.Add(parQuantity);
                updateCmd.Parameters.Add(parProductName);
                updateCmd.Parameters.Add(parDimension);

                insertCmd.CommandText = "INSERT INTO invoiceiddescription (InvoiceID, Quantity, Classifier, Weight, ProductName, " +
                    "Dimension, PricePerUnit, UnitName) " +
                    "VALUES (?InvoiceID, ?Quantity, ?Classifier, ?Weight, ?ProductName, ?Dimension, ?PricePerUnit, ?UnitName)";

                updateCmd.CommandText = "UPDATE product SET ItemsRemainVat = itemsRemainVat - ?Quantity " +
                    "WHERE Name = ?ProductName AND Dimension = ?Dimension";

                getInvoiceIDCmd.CommandText = "SELECT @@IDENTITY AS 'LastID'";
                MySqlDataReader dbReader = getInvoiceIDCmd.ExecuteReader();
                dbReader.Read();
                lastInvoiceID = Int32.Parse(dbReader.GetValue(0).ToString());
                dbReader.Dispose();

                for (int i = 0; i < AddInvoiceFormDataGridView.RowCount; i++)
                {
                    if (!(bool)AddInvoiceFormDataGridView[0, i].Value)
                        continue;

                    parInvoiceID.Value = lastInvoiceID;
                    parQuantity.Value = AddInvoiceFormDataGridView[1, i].Value.ToString();
                    parClassifier.Value = AddInvoiceFormDataGridView[2, i].Value.ToString();

                    if (AddInvoiceFormDataGridView[3, i].Value.ToString() == "")
                        parWeight.Value = null;
                    else
                        parWeight.Value = AddInvoiceFormDataGridView[3, i].Value.ToString();

                    parProductName.Value = AddInvoiceFormDataGridView[4, i].Value.ToString();
                    parDimension.Value = AddInvoiceFormDataGridView[5, i].Value.ToString();
                    parPricePerUnit.Value = AddInvoiceFormDataGridView[6, i].Value.ToString();
                    parUnitName.Value = AddInvoiceFormDataGridView[7, i].Value.ToString();

                    insertCmd.ExecuteNonQuery();
                    updateCmd.ExecuteNonQuery();
                }

                requisitionUpdateCmd.CommandText = "UPDATE requisitionidcustomername SET IsInvoice = true " +
                    "WHERE RequisitionID = " + _requisitionID;
                requisitionUpdateCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
                ShowCompleteMessage(lastInvoiceID);
            }
        }


        private void OpenReport(int reportID)
        {
            TaxDeliveryReceiptSelectionForm taxDeliveryReceiptSelectionForm
                = new TaxDeliveryReceiptSelectionForm();
            ShowReportForm showReportForm = new ShowReportForm(_connectionString);

            switch (taxDeliveryReceiptSelectionForm.ShowDialog())
            {
                case DialogResult.OK:
                    string branchName;
                    if (taxDeliveryReceiptSelectionForm.MainCompanyRadioButton.Checked)
                        branchName = "สำนักงานใหญ่";
                    else
                        branchName = taxDeliveryReceiptSelectionForm.BranchNameTextBox.Text;

                    if (taxDeliveryReceiptSelectionForm.TaxDeliveryOrigRadioButton.Checked)
                        showReportForm.setReportToShow(3, reportID, true, true, branchName);
                    else if (taxDeliveryReceiptSelectionForm.TaxDeliveryCopyRadioButton.Checked)
                        showReportForm.setReportToShow(3, reportID, false, true, branchName);
                    else if (taxDeliveryReceiptSelectionForm.ReceiptOrigRadioButton.Checked)
                        showReportForm.setReportToShow(4, reportID, true, true, branchName);
                    else
                        showReportForm.setReportToShow(4, reportID, false, true, branchName);

                    showReportForm.LoadReport();
                    showReportForm.ShowDialog();
                    break;
                default:
                    break;
            }
        }

        private void ShowCompleteMessage(int reportID)
        {
            AddCompleteForm addCompleteForm = new AddCompleteForm();
            switch (addCompleteForm.ShowDialog())
            {
                case DialogResult.OK:
                    FormChangedEvent("INVOICE_SELECTION", null);
                    OpenReport(reportID);
                    break;
                default:
                    FormChangedEvent("INVOICE_SELECTION", null);
                    break;
            }
        }

        private void AddInvoiceFormDataGridView_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
        {
            if (UnitComboBox.SelectedIndex == -1)
                return;

            string unitSelected = _dataGridViewDataTable.Rows[e.Cell.RowIndex][COLUMN_7_NAME].ToString();

            PriceNumericUpDown.Value = Convert.ToDecimal(_priceDictionary[e.Cell.RowIndex][unitSelected].ToString());

            UnitComboBox.Items.Clear();
            foreach (string key in _priceDictionary[e.Cell.RowIndex].Keys)
                UnitComboBox.Items.Add(key);
            UnitComboBox.SelectedItem = unitSelected;
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            string pricePerUnit = PriceNumericUpDown.Value.ToString();
            string unitSelected = UnitComboBox.Items[UnitComboBox.SelectedIndex].ToString();

            int rowIndex = AddInvoiceFormDataGridView.CurrentCell.RowIndex;

            _priceDictionary[rowIndex][unitSelected] = pricePerUnit;

            _dataGridViewDataTable.Columns[COLUMN_6_NAME].ReadOnly = false;
            _dataGridViewDataTable.Columns[COLUMN_7_NAME].ReadOnly = false;
            _dataGridViewDataTable.Columns[COLUMN_8_NAME].ReadOnly = false;

            _dataGridViewDataTable.Rows[rowIndex][COLUMN_6_NAME] = pricePerUnit;
            _dataGridViewDataTable.Rows[rowIndex][COLUMN_7_NAME] = unitSelected;

            if (unitSelected == "kg")
            {
                double pricePerWeight = Double.Parse(pricePerUnit);
                double weight = Double.Parse(_dataGridViewDataTable.Rows[rowIndex][COLUMN_3_NAME].ToString());

                double amount = pricePerWeight * weight;
                _dataGridViewDataTable.Rows[rowIndex][COLUMN_8_NAME] = amount.ToString("N2", CultureInfo.InvariantCulture);
            }
            else
            {
                double pricePerItem = Double.Parse(pricePerUnit);
                int quantity = Int32.Parse(_dataGridViewDataTable.Rows[rowIndex][COLUMN_1_NAME].ToString());

                double amount = pricePerItem * quantity;
                _dataGridViewDataTable.Rows[rowIndex][COLUMN_8_NAME] = amount.ToString("N2", CultureInfo.InvariantCulture);
            }

            _dataGridViewDataTable.Columns[COLUMN_6_NAME].ReadOnly = true;
            _dataGridViewDataTable.Columns[COLUMN_7_NAME].ReadOnly = true;
            _dataGridViewDataTable.Columns[COLUMN_8_NAME].ReadOnly = true;

            CalculateTotal();

            (new ErrorAndCompleteFrom()).ShowDialog();
        }

        private void UnitComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            string unitSelected = UnitComboBox.Items[UnitComboBox.SelectedIndex].ToString();

            int rowIndex = AddInvoiceFormDataGridView.CurrentCell.RowIndex;

            PriceNumericUpDown.Value = Convert.ToDecimal(_priceDictionary[rowIndex][unitSelected].ToString());
        }

        private void AddInvoiceFormDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0)
                return;

            if ((bool)((DataGridViewCheckBoxCell)AddInvoiceFormDataGridView[0, e.RowIndex]).Value)
                _dataGridViewDataTable.Rows[e.RowIndex][0] = false;
            else
                _dataGridViewDataTable.Rows[e.RowIndex][0] = true;

            CalculateTotal();
        }

        private void AddInvoiceFormDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0)
                return;

            if ((bool)((DataGridViewCheckBoxCell)AddInvoiceFormDataGridView[0, e.RowIndex]).Value)
                _dataGridViewDataTable.Rows[e.RowIndex][0] = false;
            else
                _dataGridViewDataTable.Rows[e.RowIndex][0] = true;

            CalculateTotal();
        }

        private void SaveButton_MouseHover(object sender, EventArgs e)
        {
            HelpToolTip.Show("บันทึกข้อมูล", (Button)sender);
        }

        private void DeliveryCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            DeliveryNumericUpDown.Visible = DeliveryCheckBox.Checked;
            UnitLabel.Visible = DeliveryCheckBox.Checked;
        }

        private void IncludeVatCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            /*if (IncludeVatCheckBox.Checked)
            {
                _dataGridViewDataTable.Columns[COLUMN_6_NAME].ColumnName = "ราคาหน่วยละ (รวม Vat)";
                COLUMN_6_NAME = "ราคาหน่วยละ (รวม Vat)";
                CalculateTotal();
            }
            else
            {
                _dataGridViewDataTable.Columns[COLUMN_6_NAME].ColumnName = "ราคาหน่วยละ (ไม่รวม Vat)";
                COLUMN_6_NAME = "ราคาหน่วยละ (ไม่รวม Vat)";
                CalculateTotal();
            }*/
            CalculateTotal();
        }

        private void IncludeVatUpDown_ValueChanged(object sender, EventArgs e)
        {
            var s = sender as System.Windows.Forms.NumericUpDown;
            if (s != null)
            {
                Utility.SaveDefaultVat((int)s.Value);
                CalculateTotal();
            }
        }
    }
}